package com.gouda.temporary.service;

import com.gouda.temporary.context.ContextCode;
import com.gouda.temporary.utils.CacheUtils;
import com.gouda.temporary.utils.OpenWxUtils;
import com.gouda.temporary.vo.TempHourOrders;
import com.gouda.temporary.vo.openwx.WxOwnerInfo;
import com.gouda.temporary.vo.openwx.TextMsgBody;
import com.gouda.temporary.vo.openwx.UserInfoWithCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class WeiXinService {

    private static final Logger log = LoggerFactory.getLogger(WeiXinService.class);

    public WxOwnerInfo takeOwnerInfo(String code) {
        // 获取'物业小时工'应用token
        String accessToken = CacheUtils.getCachedAccessToken();
        if (OpenWxUtils.isBlank(accessToken)) {
            return buildFailWxOwnerInfo(ContextCode.GET_ACCESS_TOKEN_FAIL);
        }

        UserInfoWithCode userInfo = OpenWxUtils.getUserInfoByCode(code);
        if (userInfo == null || userInfo.getErrcode() != null) {
            return buildFailWxOwnerInfo(ContextCode.TAKE_USER_INFO_FAIL);
        }

        // 根据userId获取其详细信息
        WxOwnerInfo wxOwnerInfo = OpenWxUtils.getUserDetailInfo(userInfo.getUserId());

        log.info(">>>>> wx-info:" + wxOwnerInfo);

        return wxOwnerInfo;
    }

    public void sendNewsMsgToOwner(String ownerId, String title, String description, String url) {
        TextMsgBody msgBody = new TextMsgBody();

        msgBody.setTouser(ownerId);
        msgBody.setAgentid(36); // '应用-物业小时工'
        msgBody.setMsgtype("news");
        msgBody.setNews(title, description, url);

        OpenWxUtils.sendTextMsgToUser(msgBody);
    }

    public void sendNewsMsgToWorker(String workerId, String title, String description, String url) {
        TextMsgBody msgBody = new TextMsgBody();

        msgBody.setTouser(workerId);
        msgBody.setAgentid(41); // '应用-小时工抢单'
        msgBody.setMsgtype("news");
        msgBody.setNews(title, description, url);

        OpenWxUtils.sendTextMsgToUser(msgBody);
    }


    public void sendNewsMsgToPartID(String partId, String title, String description, String url) {
        TextMsgBody msgBody = new TextMsgBody();

        msgBody.setToparty(partId);
        msgBody.setAgentid(41); // '应用-小时工抢单'
        msgBody.setMsgtype("news");
        msgBody.setNews(title, description, url);

        OpenWxUtils.sendTextMsgToUser(msgBody);
    }


    private WxOwnerInfo buildFailWxOwnerInfo(String failCode) {
        WxOwnerInfo wxOwnerInfo = new WxOwnerInfo();
        wxOwnerInfo.setErrcode(failCode);
        return wxOwnerInfo;
    }


}
